#!/usr/bin/env python
# -*- coding: utf-8 -*-


# @Time    : 2020/5/9 14:17

import redis

import phpserialize
from common.read_base_config import ReadBaseConfig

read_base = ReadBaseConfig()


class MyRedis:
    r = None
    key = None
    value = None

    def __init__(self, db_name):
        """
        :param db_name: 0 开发用的redis  1测试框架用的redis
        """
        try:
            db_name = int(db_name)
            if db_name not in [0, 1]:
                raise ValueError('0 开发用的redis  1测试框架用的redis')
        except TypeError:
            raise ValueError('0 开发用的redis  1测试框架用的redis')

        # 初始化后自动连接
        self.connect_redis(db_name)

    def connect_redis(self, db_name):
        """
        连接redis
        :return:
        """
        redis_name = read_base.get('configuration', 'use_redis_config')
        self.r = redis.StrictRedis(
            host=read_base.get(redis_name, 'host'),
            password=read_base.get(redis_name, 'password'),
            port=read_base.get(redis_name, 'port'),
            db=db_name
        )

    def get_key(self, order_sn):
        """
        # 找到订单号对应的redis key
        :param order_sn:
        :return:
        """
        keys_list = self.r.keys('laravel_cache:*')
        for redis_key in keys_list:
            if str(order_sn) in str(redis_key):
                MyRedis.key = redis_key
                break
        if not MyRedis.key:
            raise ValueError('找不到相关订单的Redis key，请等待或者检查订单信息')
        return MyRedis.key

    def get_value(self, key):
        """
        :param key:
        :return:
        """
        value = self.r.get(key)
        if type(value) == bytes:
            value = value.decode(encoding="utf-8")
            return value
        else:
            return value

    def get_php_value(self):
        """
        key对应的值
        :return:
        """
        self.value = self.r.get(self.key)

        php_decode = phpserialize.loads(self.value, decode_strings=True)
        MyRedis.value = php_decode
        print('反序列化后信息:' + str(php_decode))
        return php_decode

    def set_value(self, redis_key, redis_value):
        if type(redis_value) == bytes:
            redis_value = redis_value.decode(encoding="utf-8")
        elif type(redis_value) == dict:
            redis_value = phpserialize.dumps(redis_value)
            redis_value = redis_value.decode(encoding="utf-8")
        else:
            raise ValueError('请传入bytes或者dict类型')
        print('修改后信息:' + str(redis_value))
        self.r.set(redis_key, redis_value)

    def get_keys(self):
        """
        :return: 返回键组
        """
        bytes_values = self.r.keys('mock_test_orders:*')
        str_values = list()
        for value in bytes_values:
            if type(value) == bytes:
                value = value.decode(encoding="utf-8")
                str_values.append(value)
            else:
                str_values.append(value)

        return str_values


if __name__ == '__main__':
    from common.utils import Utils

    my_redis = MyRedis(1)
    a = my_redis.get_keys()
    # print(a)
    order_info = eval(my_redis.get_value('mock_test_orders:20200910114857_CaoCao_20223099'))
    print(order_info)
    # 酒店
    # key = my_redis.get_key('152008251139421913')
    # value = my_redis.get_php_value()
    # value['departure_date'] = Utils.get_calculate_datetime(-1)
    # value['list_extend']['departure_date'] = Utils.get_calculate_datetime(-1)
    # my_redis.set_value(key, value)
    #
    # 机票
    # key = my_redis.get_key(142008251100048457)
    # value = my_redis.get_value()
    # value['list_extend']['order_flight_info']['arrive_date'] = Utils.get_calculate_datetime(-1)[:10]
    # my_redis.set_value(key, value)
